﻿using SketchUpAPI.NET.Enums;
using SketchUpAPI.NET.SketchUp.Exception;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace SketchUpAPI.NET.Objects
{
    /// <summary>
    /// 物件集合迭代器
    /// </summary>
    /// <remarks>对 SketchUpAPI 中的 SUEntityListIteratorRef 包装</remarks>
    public class EntityListIterator : ObjectBase, IEnumerator<Entity>
    {
        #region API 函数
        /// <summary>
        /// 创建一个迭代器
        /// </summary>
        /// <param name="iterator"></param>
        /// <returns></returns>
        [DllImport(LIB)]
        static extern SUResult SUEntityListIteratorCreate(out IntPtr iterator);

        /// <summary>
        /// 释放资源
        /// </summary>
        /// <param name="iterator"></param>
        /// <returns></returns>
        [DllImport(LIB)]
        static extern SUResult SUEntityListIteratorRelease(ref IntPtr iterator);

        /// <summary>
        /// 获取当前物体
        /// </summary>
        /// <param name="iterator"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        [DllImport(LIB)]
        static extern SUResult SUEntityListIteratorGetEntity(IntPtr iterator, out IntPtr entity);

        /// <summary>
        /// 下一个
        /// </summary>
        /// <param name="iterator"></param>
        /// <returns></returns>
        [DllImport(LIB)]
        static extern SUResult SUEntityListIteratorNext(IntPtr iterator);

        /// <summary>
        /// 是否超出范围
        /// </summary>
        /// <param name="iterator"></param>
        /// <param name="in_range"></param>
        /// <returns></returns>
        [DllImport(LIB)]
        static extern SUResult SUEntityListIteratorIsInRange(IntPtr iterator, out bool in_range);
        #endregion

        internal EntityListIterator(IntPtr id) => Id = id;

        public bool MoveNext()
        {
            SketchUpExceptionHelper.ThrowSUResult(SUEntityListIteratorNext(Id));
            SketchUpExceptionHelper.ThrowSUResult(SUEntityListIteratorIsInRange(Id, out bool in_range));
            return in_range;
        }

        public void Reset()
        {
            throw new NotImplementedException();
        }

        public Entity Current
        {
            get
            {
                SketchUpExceptionHelper.ThrowSUResult(SUEntityListIteratorGetEntity(Id, out IntPtr entity));
                return new Entity(entity);
            }
        }

        object IEnumerator.Current => Current;

        public override void Dispose()
        {
            SketchUpExceptionHelper.ThrowSUResult(SUEntityListIteratorRelease(ref Id));
        }
    }
}